package com.nuanshui.heatedloan.extension.filter;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.LogUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.extension.CustomHttpRequest;
import com.nuanshui.heatedloan.extension.CustomHttpResponse;

public class SessionFilter extends OncePerRequestFilter {

    @SuppressWarnings("unused")
	private Logger log = LoggerFactory.getLogger(getClass());

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		    try {
				request.setAttribute(GlobalParam.USER_AGENT, getUserAgent(request));
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				request.setAttribute(GlobalParam.USER_AGENT, new UserAgent());
			} catch (InvocationTargetException e) {
				e.printStackTrace();
				request.setAttribute(GlobalParam.USER_AGENT, new UserAgent());
			}
		    CustomHttpRequest req = new CustomHttpRequest(request, response);
		    CustomHttpResponse resp = new CustomHttpResponse(response, request);
		    try {
		    	 filterChain.doFilter(req,resp);    
			} catch (Exception e) {
				e.printStackTrace();
			}
	        
 	}


 	private void copyProp(UserAgent userAgent,String props) throws InvocationTargetException, IllegalAccessException {
		String strs[] = 	 props.split(",");
		for(String str :strs) {
			String item[] =  str.split(":");
			String name = item[0].trim();
			String value = null;
			if(item.length>1) value =  item[1].trim();
			BeanUtils.setProperty(userAgent, name, value);
		}
	}
	
	private UserAgent getUserAgent(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException {
		String userAgentStr = request.getHeader("User-Agent");
		UserAgent userAgent = new UserAgent();
		if(StringUtils.isNotEmpty(userAgentStr)&&userAgentStr.indexOf("safeToken")>0) {
			copyProp(userAgent,userAgentStr);
		}

		String appInfo = request.getHeader("App-Info");
		if(StringUtils.isNotEmpty(appInfo) &&appInfo.indexOf("safeToken")>0)
		{
			copyProp(userAgent,appInfo);
		}

		LogUtil.info(log,"SessionFilter-UserAgent:", JSON.toJSONString(userAgent));


		return userAgent;
	}
	

}
